export default {
  data() {
    return {
      // 购物车缓存 Storage 名称
      shopCartStorageName: 'roomsShopCart',
      // 选中套餐
      currentMeal: null,
      // 选中商品 - 套餐配送详情列表
      selectMealFormStatistics: { originMealForm: [], groups: [], goods: [] }
    }
  },
  computed: {
    loginInfo() {
      return this.$store.getters.loginInfo
    }
  },
  methods: {
    // 展示套餐配送列表
    showForm(goods, id, ifManualAdd) {
      this.currentMeal = goods

      if (!id) return this.$msg('text', '商品id为空')

      const bid = this.$format(goods, 'bid') // 推荐套餐使用

      this.getMealDetail(id, bid).then(mealForm => {
        if (!mealForm) {
          return this.$msg('text', '套餐数据为空')
        }

        this.selectMealFormStatistics = mealForm.reduce(
          (pre, item, index) => {
            if (item.goods) {
              item.goods = item.goods.map(goodItem => {
                goodItem.selectNumber = 0
                goodItem.singleNumber = goodItem.number
                return goodItem
              })
            } else {
              item.goods = []
            }

            if (!item.setsubname) {
              item.setsubname = '组' + index
            }

            pre.goods.push(item.goods)
            pre.groups.push(item.setsubname)
            pre.originMealForm.push(item)
            return pre
          },
          { goods: [], groups: [], originMealForm: [] }
        )

        if (this.$refs.mealFormModal) {
          this.$refs.mealFormModal.open({ ifManualAdd })
        } else {
          console.log('请先在页面中添加 modal-meal-form 组件')
        }
      })
    },

    /**
     * 页面初始化
     * 1. 读取缓存中购物车对象数据 + 购物车数据
     * 2. 将购物车的选中数据，初始化到接口获取的商品列表中
     */
    init(goodsList = this.goodsList, forcedRefresh = false) {
      let { allCarts, currentRoomShopCart, currentShopCart } = this.getCurrentRoomShopCart()

      this.currentRoomShopCart = currentRoomShopCart
      this.currentShopCart = currentShopCart

      if (currentShopCart && currentShopCart.length > 0) {
        for (let i in currentShopCart) {
          for (let j in goodsList) {
            // 判断等于 goodsid 是为了兼容推荐套餐里面添加的商品。推荐套餐添加过来的 goodsid 才是 shop 页面获取菜品拿到的 id . ( 可查询 || .goodsid 筛选 )
            if (goodsList[j].id === currentShopCart[i].id || goodsList[j].id === currentShopCart[i].goodsid) {
              goodsList[j].selectNumber = currentShopCart[i].selectNumber
            }
          }
        }

        /**
         * 如果是套餐搜索内的数据更新，先不要执行除去 selectNumber 为 0 的商品。因为这里如果直接清空掉了，shop 页面的商品列表的数据就会因为已经移除了商品而无法同步移除的商品导致
         * 以及移除的商品在列表中依旧显示 1 件
         * 且这个方法会在 搜索的商品更新完成之后，再次执行主列表的更新而得到同步
         */
        if (!forcedRefresh) {
          // 购物车移除 selectNumber 为 0 的商品数据
          this.currentShopCart = currentShopCart = this.currentShopCart.filter(item => {
            return item.selectNumber > 0
          })
        }

        // 通过对象引用的更新，同步从缓存中取出来的房台购物车对象数据
        currentRoomShopCart.shopCart = currentShopCart

        // 购物车商品数据缓存至本地
        uni.setStorageSync(this.shopCartStorageName, allCarts)
      }

      // 是否强制刷新
      if (forcedRefresh) {
        this.goodsList = JSON.parse(JSON.stringify(goodsList))
      }

      this.setLabelNumber()

      // 移除最后一件商品后关闭购物车
      if (currentShopCart && currentShopCart.length === 0) {
        this.hideShoppingCar()
      }
    },

    // 计算每类商品购买的总数
    setLabelNumber() {
      // 计算每一类购买商品的总数量
      for (let j in this.categoryList) {
        let selectNumber = 0

        for (var i in this.currentShopCart) {
          if (this.currentShopCart[i].STypeId == this.categoryList[j].id) {
            selectNumber += this.currentShopCart[i].selectNumber
          }
        }

        this.categoryList[j].selectNumber = selectNumber
      }
    },

    // 获取当前房间的购物车对象 + 购物车数组
    getCurrentRoomShopCart() {
      let currentRoomShopCart = null // roomShopCart: { roomid: '', shopCart: [] }
      let currentShopCart = null // shopCart: []

      // 存储的是所有 [{房台的信息 + 购物车数据}]
      const allCarts = uni.getStorageSync(this.shopCartStorageName) || []

      // 总购物车不存在 ，当前房台购物车不存在
      if (!allCarts || (allCarts && allCarts.length === 0)) {
        return { allCarts, currentRoomShopCart, currentShopCart }
      }

      /**
       * 根据总购物车缓存数据判断是否有本房台的购物车对象
       * 如果有的话赋值给 currentRoomShopCart ， 如果没有 currentRoomShopCart 为 null
       */
      for (let i in allCarts) {
        if (allCarts[i].roomid === this.loginInfo.roomid) {
          currentRoomShopCart = allCarts[i].shopCart ? allCarts[i] : null
          currentShopCart = allCarts[i].shopCart ? allCarts[i].shopCart : null
          break
        }
      }

      return { allCarts, currentRoomShopCart, currentShopCart }
    },

    // 获取例送规则
    getLscs(param, type, defaultData) {
      if (!param) return defaultData || ''

      param = String(param)

      if (!type) {
        console.log('请填写取值类型')
        return defaultData || ''
      }

      if (type === '满') {
        return Number(param.substring(0, 1)) || defaultData || 1
      }

      if (type === '买') {
        return Number(param.substring(1, 3)) || defaultData || ''
      }

      if (type === '送') {
        return Number(param.substring(3, 5)) || defaultData || ''
      }
    },

    // 根据选中数量与例送规则算出应该送出的例送数量
    getLscsNumber(selectNumber, lscs) {
      const buy = this.getLscs(lscs, '买') || ''
      const send = this.getLscs(lscs, '送') || ''
      if (!lscs || !buy || !send) return 0
      return parseInt(selectNumber / buy) * send
    },

    // 是否为套餐属性
    isMeal(val) {
      const meal = 1
      return val === meal
    },

    mealFormModalClose() {
      this.selectMealFormStatistics = null
    }
  }
}
